//
//  XMSearchViewController.m
//  BigJoy
//
//  Created by Rowling on 2017/6/19.
//  Copyright © 2017年 Rowling. All rights reserved.
//

#import "XMSearchViewController.h"
#import "CommonCollectionViewCell.h"
#import "SearchSectionHeaderView.h"
#import "UserCollectionViewCell.h"

typedef enum{
    NOEditing = 0,
    isEditing = 1,
    endSearch = 2
}SearchType;

@interface XMSearchViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate>
{
    SearchType searchType;
}

@property (nonatomic,strong) NSMutableArray *historyDataArray;
@property (nonatomic,strong) UICollectionView * collectionView;
@property (weak, nonatomic) IBOutlet UITextField *searchTextFeild;

@end

@implementation XMSearchViewController
- (IBAction)backButtonClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES ];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    searchType = 0;
    self.historyDataArray = [XMSuperHelper getSearchHistory];
    [self setUI];
    [self addTapToDealWithEndEditng];
}

-(void)setUI {
    self.XMTableview.frame = CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64);
    [self.view addSubview:self.XMTableview];
    UIImageView * searchImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"search"]];
    UIView * leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [leftView addSubview:searchImageView];
    searchImageView.center = leftView.center;
    UIView * lineView = [UIView new];
    [leftView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(leftView);
        make.centerY.equalTo(leftView);
        make.width.equalTo(@0.5);
        make.height.equalTo(@14);
    }];
    lineView.backgroundColor = XMColor(220, 220, 220);
    self.searchTextFeild.leftView = leftView;
    self.searchTextFeild.leftViewMode = UITextFieldViewModeAlways;
//    [self cutomNavBarView];
//    [self.serchView.searchButton setTitle:@"搜索" forState:UIControlStateNormal];
//    [self.serchView.searchButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [self.serchView.searchButton addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
//    @weakify(self);
//    [[self.serchView.leftButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
//        @strongify(self);
//        [self.navigationController popViewControllerAnimated:YES];
//    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (searchType == NOEditing) {
        return  [self.historyDataArray count] + 1;
    }
    return 10;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (searchType) {
        case NOEditing:
        {
            return [self cellForRowOfHistroyWithTalview:tableView indexpath:indexPath];
        }
            break;
        case endSearch:
        {
            UITableViewCell * cell = [[UITableViewCell alloc]init];
            return cell;
        }
            break;
            
        default:{
            UITableViewCell * cell = [[UITableViewCell alloc]init];
            return cell;
        }
            break;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
    switch (searchType) {
        case NOEditing:
        {
            if (self.historyDataArray.count > 0 && indexPath.row > 0) {
                self.searchTextFeild.text = self.historyDataArray[indexPath.row - 1];
            }
        }
            break;
        case endSearch:
        {
            
        }
            break;
            
        default:{
        }
            break;
    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return  [[UIView alloc]init];
}



//cellforRow搜索历史
-(UITableViewCell *)cellForRowOfHistroyWithTalview:(UITableView*)tableView indexpath:(NSIndexPath *)indexPath {
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"his"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"his"];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.textColor = XMColor(157, 157, 157);
    }
    if (indexPath.row == 0) {
        cell = [[UITableViewCell alloc]init];
        UIButton * btn = [UIButton new];
        [btn setImage:[UIImage imageNamed:@"trash"] forState:UIControlStateNormal];
        [btn sizeToFit];
        [cell.contentView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(cell.contentView);
            make.right.equalTo(cell.contentView).offset(-15);
        }];
        @weakify(self);
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self);
            [XMUserDefaults removeObjectForKey:SearchHistory];
            [self reloadDataSafe];
        }];
        cell.textLabel.text = @"清空历史记录";
        cell.textLabel.font = [UIFont systemFontOfSize:11];
        cell.textLabel.textColor = [UIColor colorForHex:@"666666"];
    }else {
        cell.textLabel.text = self.historyDataArray[indexPath.row - 1];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//#pragma -mark:buttonClick 
//-(void)searchButtonClick {
//    [self.serchView.searchBar endEditing:YES];
//    NSString * searchStr = self.serchView.searchBar.text;
//    if ([searchStr isEqualToString:@""]) {
//        [Apputil showError:@"请输入搜索内容"];
//        return;
//    }
//    // 在这里掉用搜索的接口
//    [self.XMTableview removeFromSuperview];
//    [self.view addSubview:self.collectionView];
//    
//    //save history
//    for (NSString * str in [XMSuperHelper getSearchHistory]) {
//        if ([searchStr isEqualToString:str]) {
//            return;
//        }
//    }
//    [XMSuperHelper saveSearchWithStr:searchStr];
//    [self reloadDataSafe];
//}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if ([searchText isEqualToString:@""]) {
        [self.collectionView removeFromSuperview];
        [self.view addSubview:self.XMTableview];
    }
}

//防止数据出错调用该方法来刷新tableView
-(void)reloadDataSafe {
    self.historyDataArray = [XMSuperHelper getSearchHistory];
    [self.XMTableview reloadData];
}

#pragma -mark: 搜索之后。出现collectionView为什么做的这么麻烦。就是喜欢麻烦
-(UICollectionView *)collectionView {
    if (_collectionView == nil) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = XMColor(240, 240, 240);
        //register
        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([CommonCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:@"Cell"];
        [_collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([UserCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:@"UCell"];
        [self.collectionView registerNib:[UINib nibWithNibName:@"SearchSectionHeaderView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UID"];
        
    }
    return _collectionView;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
        return  CGSizeMake(SCREEN_WIDTH, 40);
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return  CGSizeMake(SCREEN_WIDTH, 50);
    } else {
        return  CGSizeMake((SCREEN_WIDTH - XMW(30)  ) / 2, (SCREEN_WIDTH - XMW(40) ) / 2);
    }
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    if (section == 0) {
        return 1;
    }else {
        return  XMW(10);
    }
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    SearchSectionHeaderView * reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UID" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        reusableView.label.text = @"用户";
    }else {
        reusableView.label.text = @"作品";
    }
    return reusableView;
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return 4;
    }
    if (section == 1) {
        return 10;
    }
    return 10;
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 0) {
      return UIEdgeInsetsMake(1,0,1,0);
    }else {
      return UIEdgeInsetsMake(XMH(10), XMW(10), 0, XMW(10));
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        UserCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UCell" forIndexPath:indexPath];
        return cell;
    }else {
        CommonCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
        return cell;
    }
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.view endEditing:YES];
}

//处理endEditing
-(void)addTapToDealWithEndEditng {
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]init];
    [tap addTarget:self action:@selector(tap)];
    [self.XMTableview addGestureRecognizer:tap];
    UITapGestureRecognizer * tapTwo = [[UITapGestureRecognizer alloc]init];
    [tapTwo addTarget:self action:@selector(tap)];
    [self.collectionView addGestureRecognizer:tapTwo];
    tap.delegate = self;
    tapTwo.delegate = self;
}

-(void)tap {
    [self.view endEditing:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 输出点击的view的类名
//    NSLog(@"%@", NSStringFromClass([touch.view class]));
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UICollectionView"] || [NSStringFromClass([touch.view class]) isEqualToString:@"UITableView"] ) {
        return YES;
    }
    return  NO;
}
// 搜索
- (IBAction)searchButtonClick:(id)sender {
    //save history
    for (NSString * str in [XMSuperHelper getSearchHistory]) {
        if ([self.searchTextFeild.text isEqualToString:str]) {
            return;
        }
    }
    [XMSuperHelper saveSearchWithStr:self.searchTextFeild.text];
    [self reloadDataSafe];
}


@end
